PID=$(ps -aux |grep robot | awk '{print $2 }')
#echo ${PID}
#echo ${PID} > temp
#echo ${#PID[@]}

PID_NAME=$(ps -aux |grep robot | awk '{print $11 }')
#echo ${PID_NAME} ${#PID_NAME[@]}
#echo ${PID_NAME[0]}

if [ $# -eq 0 ];
then
	echo "input error 0, eg: ./upgrade.sh /dev/ttyTHSx xx.bin"
	exit
else
	if [[ $1 == /dev/ttyTHS* ]];then
		echo "IAP port:"$1
	else
		echo "$1 input error 1, eg: ./upgrade.sh /dev/ttyTHSx xx.bin"
		exit
	fi
	if [[ $2 != *.bin ]];then
		echo "$2 input error 2, eg: ./upgrade.sh /dev/ttyTHSx xx.bin"
		exit
	else
		echo "IAP bin :"$2
	fi	
fi

if [[ "${PID_NAME[@]}"  =~ "/opt/cr300c_robot_image/cr300c_robot_image" ]]; then
	echo "excute systemctl stop yt_cr300c_robot.service"
	sudo systemctl stop yt_cr300c_robot.service
elif [[ -f "/bin/robotMonitor" ]]; then
	echo "excute kill /bin/robotMonitor pid"
	if [[ ${#PID[@]} > 1 ]];
	then
		echo ${PID}
        sudo kill ${PID}
fi


#else
	#echo "ok"
	#exit
fi

#sudo ./uart_iap /dev/ttyTHS2 fw_YT_CR300_APP_0x8010000_Update_*
sudo ./uart_iap $1 $2

sleep 1

if [[ -f "/opt/cr300c_robot_image/cr300c_robot_image" ]]; then
	#echo "excute /opt/cr300c_robot_image/start_cr300c.sh"
	#sudo /opt/cr300c_robot_image/start_cr300c.sh
	echo "excute systemctl start yt_cr300c_robot.service"
	sudo systemctl start yt_cr300c_robot.service
elif [[ -f "/bin/robotMonitor" ]]; then
	echo "excute /bin/robotMonitor"
	sudo /bin/robotMonitor &
fi

